<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1200" scroll :max-height="600">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      :disabled="formDisabled"
      style="width: 99%"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="订单单号" prop="no">
            <el-input disabled v-model="formData.no" placeholder="保存时自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="采购日期" prop="orderTime">
            <el-date-picker
              v-model="formData.orderTime"
              type="date"
              value-format="x"
              placeholder="选择采购日期"
              class="!w-1/1"
              :disabled="isOtherDisabled"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="部门" prop="deptId" label-width="120">
            <el-select
              v-model="formData.deptId"
              placeholder="请选择部门"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.DEPT_MANAGE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="供应商" prop="supplierId">
            <el-select
              v-model="formData.supplierId"
              clearable
              filterable
              placeholder="请选择供应商"
              class="!w-1/1"
            >
              <el-option
                v-for="item in supplierList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="16">
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              v-model="formData.remark"
              :disabled="isOtherDisabled"
              :rows="1"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <!--          <el-form-item label="附件" prop="fileUrl">-->
          <!--            <UploadFile-->
          <!--              :is-show-tip="false"-->
          <!--              v-model="formData.fileUrl"-->
          <!--              :limit="1"-->
          <!--              :disabled="isOtherDisabled"-->
          <!--            />-->
          <!--          </el-form-item>-->
        </el-col>
      </el-row>
      <!-- 子表的表单 -->

      <div style="margin-bottom: 20px; text-align: center">
        <el-button
          type="primary"
          plain
          style="margin-right: 20px"
          @click="handleImport"
          :disabled="isOtherDisabled"
          >Excel导入附件进行采购订单</el-button
        >
      </div>

      <ContentWrap>
        <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
          <el-tab-pane label="订单产品清单" name="item">
            <PurchaseOrderItemForm
              ref="itemFormRef"
              :items="formData.items"
              :isOtherDisabled="isOtherDisabled"
              :isSupplierDisabled="isSupplierDisabled"
            />
          </el-tab-pane>
        </el-tabs>
      </ContentWrap>
      <!--      <el-row :gutter="20">-->
      <!--        <el-col :span="8">-->
      <!--          <el-form-item label="优惠率（%）" prop="discountPercent">-->
      <!--            <el-input-number-->
      <!--              v-model="formData.discountPercent"-->
      <!--              controls-position="right"-->
      <!--              :min="0"-->
      <!--              :max="100"-->
      <!--              :precision="2"-->
      <!--              placeholder="请输入优惠率"-->
      <!--              class="!w-1/1"-->
      <!--            />-->
      <!--          </el-form-item>-->
      <!--        </el-col>-->
      <!--        <el-col :span="8">-->
      <!--          <el-form-item label="税率（%）" prop="taxPercent">-->
      <!--            <el-input-number-->
      <!--              v-model="formData.taxPercent"-->
      <!--              controls-position="right"-->
      <!--              :min="0"-->
      <!--              :max="100"-->
      <!--              :precision="2"-->
      <!--              placeholder="请输入税率"-->
      <!--              class="!w-1/1"-->
      <!--            />-->
      <!--          </el-form-item>-->
      <!--        </el-col>-->
      <!--      </el-row>-->
    </el-form>
    <template #footer>
      <el-button
        @click="submitForm"
        type="primary"
        :disabled="formLoading || formType === 'detail'"
        v-if="formType !== 'detail'"
      >
        确 定
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <PurchaseImportForm ref="importFormRef" @success="importHandler" />
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { PurchaseOrderApi, PurchaseOrderVO } from '@/api/erp/purchase/applyWarehouseOrder'
import download from '@/utils/download'
import PurchaseOrderItemForm from './components/PurchaseOrderItemForm.vue'
import PurchaseImportForm from './components/PurchaseImportForm.vue'
import { SupplierApi, SupplierVO } from '@/api/erp/purchase/supplier'
import { erpPriceInputFormatter, erpPriceMultiply } from '@/utils'
import * as UserApi from '@/api/system/user'
import { AccountApi, AccountVO } from '@/api/erp/finance/account'
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'

/** ERP 销售订单表单 */
defineOptions({ name: 'PurchaseOrderForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改；detail - 详情
const formData = ref({
  id: undefined,
  supplierId: undefined,
  accountId: undefined,
  orderTime: undefined,
  deptId: undefined,
  remark: undefined,
  fileUrl: '',
  discountPercent: 0,
  taxPercent: 0,
  discountPrice: 0,
  totalPrice: 0,
  depositPrice: 0,
  items: [],
  no: undefined // 订单单号，后端返回
} as any)
const formRules = reactive({
  supplierId: [{ required: true, message: '供应商不能为空', trigger: 'blur' }],
  orderTime: [{ required: true, message: '订单时间不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '部门不能为空', trigger: 'blur' }]
})
// const disabled = computed(() => formType.value === 'detail')
const formDisabled = computed(() => {
  // 1. detail 场景：全部禁用（保持原有逻辑）
  if (formType.value === 'detail') return true
  // 2. update 场景：表单整体不禁用（为“供应商修改可用”留入口）
  if (formType.value === 'update') return false
  // 3. 其他场景（如新增 add）：全部不禁用
  return false
})

// 新增：单独控制“供应商组件”的禁用逻辑
const isSupplierDisabled = computed(() => {
  // 只有 detail 场景禁用供应商修改，update 场景允许修改
  return formType.value === 'detail'
})

// 新增：控制“非供应商组件”（产品、数量、备注等）的禁用逻辑
const isOtherDisabled = computed(() => {
  // detail / update 场景：非供应商组件全部禁用
  return formType.value === 'detail' || formType.value === 'update'
})
const formRef = ref() // 表单 Ref
const supplierList = ref<SupplierVO[]>([]) // 供应商列表
const accountList = ref<AccountVO[]>([]) // 账户列表
const userList = ref<UserApi.UserVO[]>([]) // 用户列表

/** 子表的表单 */
const subTabsName = ref('item')
const itemFormRef = ref()

/** 计算 discountPrice、totalPrice 价格 */
watch(
  () => formData.value,
  (val) => {
    if (!val) {
      return
    }
    const totalPrice = val.items.reduce((prev, curr) => prev + curr.totalPrice, 0)
    const discountPrice =
      val.discountPercent != null ? erpPriceMultiply(totalPrice, val.discountPercent / 100.0) : 0
    formData.value.discountPrice = discountPrice
    formData.value.totalPrice = totalPrice - (discountPrice || 0)
  },
  { deep: true }
)

const deptList = ref<Tree[]>([]) // 树形结构
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await PurchaseOrderApi.getPurchaseOrder(id)
    } finally {
      formLoading.value = false
    }
  }
  // 加载供应商列表
  supplierList.value = await SupplierApi.getSupplierSimpleList()
  // 加载用户列表
  userList.value = await UserApi.getSimpleUserList()
  // 加载部门列表
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  // 加载账户列表
  accountList.value = await AccountApi.getAccountSimpleList()
  const defaultAccount = accountList.value.find((item) => item.defaultStatus)
  if (defaultAccount) {
    formData.value.accountId = defaultAccount.id
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 导入Excel 模板 */
const importHandler = (data: any) => {
  if (data.failList.length > 0) {
    ElMessageBox.alert(data.failList[0], '导入失败', {
      confirmButtonText: 'OK'
    })
  } else {
    formData.value.items = data.successList
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  await itemFormRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PurchaseOrderVO
    if (formType.value === 'create') {
      await PurchaseOrderApi.createPurchaseOrder(data)
      message.success(t('common.createSuccess'))
    } else {
      await PurchaseOrderApi.updatePurchaseOrder(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    supplierId: undefined,
    accountId: undefined,
    orderTime: undefined,
    deptId: undefined,
    remark: undefined,
    fileUrl: '',
    discountPercent: 0,
    taxPercent: 0,
    discountPrice: 0,
    totalPrice: 0,
    depositPrice: 0,
    items: []
  }
  formRef.value?.resetFields()
}
</script>
